// import React from 'react';
import React from './ireact/react';
// import ReactDOM from 'react-dom';
import ReactDOM from './ireact/react-dom';

const PersonContext = React.createContext({}); //{}
const HeadContext = React.createContext({}); //{}
const BodyContext = React.createContext({}); //{}

class Person extends React.Component {
  state = {color: 'red'}
  changeColor = (color) => this.setState({color});

  render() {
    const contextValue = {name: 'Person', color: this.state.color, changeColor: this.changeColor}

    return (
      <PersonContext.Provider value={contextValue}>
        <div style={{border: `5px solid ${this.state.color}`, padding: `5px`, width: '200px'}}>
          Person
          <Head/>
          <Body/>
        </div>
      </PersonContext.Provider>
    )
  }
}

class Head extends React.Component {
  static contextType = PersonContext

  render() {
    const contextValue = {name: 'Head'}

    return (
      <HeadContext.Provider value={contextValue}>
        <div style={{border: `5px solid ${this.context.color}`, padding: `5px`}}>
          Head
          <Eye/>
        </div>
      </HeadContext.Provider>
    )
  }
}

class Eye extends React.Component {
  static contextType = PersonContext

  render() {
    return (
      <div style={{border: `5px solid ${this.context.color}`, padding: `5px`}}>
        眼睛
      </div>
    )
  }
}

/*class Body extends React.Component {
  static contextType = PersonContext

  render() {
    return (
      <div style={{border: `5px solid ${this.context.color}`, padding: `5px`}}>
        Body
        <Arm/>
      </div>
    )
  }
}*/
function Body(props) {
  return (
    <PersonContext.Consumer>
      {
        contextValue => (
          <div style={{border: `5px solid ${contextValue.color}`, padding: `5px`}}>
            Body
            <Arm/>
          </div>
        )
      }
    </PersonContext.Consumer>
  );
}

class Arm extends React.Component {
  static contextType = PersonContext

  render() {
    return (
      <div style={{border: `5px solid ${this.context.color}`, padding: `5px`}}>
        胳膊
        <button onClick={() => this.context.changeColor('red')}>变红</button>
        <button onClick={() => this.context.changeColor('green')}>变绿</button>
      </div>
    )
  }
}

ReactDOM.render((
  <Person/>
), document.getElementById('root'));
